<template>
  <div
    class="chatContent width_100 "
    @click="$store.commit('common/set_showLittlePopup')"
    @contextmenu.prevent.capture="hideRightList"
  >
    <div class="content self_scroll chat_content" ref="messageContent" @wheel="showHistory">
      <div
        class="userMessageBox"
        v-for="item in messages"
        :key="item.msg_id"
      >
        <user-message
          :id="item.id"
          :type="item.type"
          :msg="item.msg"
          :is-self="item.isSelf"
          :imgSrc="item.imgSrc"
          :imgWidth="item.img_width"
          :imgHeight="item.img_height"
          :fileId="item.file_id"
          :fileSize="item.file_size"
          :fileName="item.file_name"
          :voice-file="item.voiceSrc"
          :msgId="item.msg_id"
          :timestamp="item.timestamp"
          :listened="item.listened"
          :voice-length="item.voice_length"
          :req-id="item.reqId"
          :call-state="item.callState"
          :duration="item.duration"
          :noticeType="item.noticeType"
          :cfName="item.cf_name"
          :cfSponsorName="item.cf_sponsor_name"
          :cfPlanParticipantCount="item.cf_plan_participant_count"
          v-if="!item.special"
        ></user-message>
        <special-message
          v-else
          :messageType="item.type"
          :timestamp="item.msg_id"
          :withdrawer="item.withdrawer"
          :isSelf="item.isSelf"
          :sponsor="item.sponsor"
          :inviter="item.inviter"
          :invitees="item.invitees"
          :exit-user="item.exitUser"
          :kicking-user="item.kickingUser"
        ></special-message>
      </div>
    </div>
    <min-dialog-box :dialogData="dialogData" v-if="deleteMsgID" @confirmBtnEvent="confirmDelete" @cancelBtnEvent="cancelDelete"></min-dialog-box>
  </div>
</template>

<script>
import userMessage from './components/userMessage'
import specialMessage from './components/specialMessage'
import { sendSock } from '../../../../../utils/socketSend'
// import { sendSock } from '@/utils/socketSend'
export default {
  components: {
    userMessage,
    specialMessage
  },
  data () {
    return {
      userMsgId: '',
      infoLeft: '',
      infoTop: '',
      // 防抖时间
      timer: null,
      // 确认删除消息data
      dialogData: {
        mainTips: ['确认删除该条消息？'],
        btnList: [{
          name: '确定',
          color: 'blue',
          type: 'confirm'
        }, {
          name: '取消',
          color: 'white',
          type: 'cancel'
        }]
      }
    }
  },
  computed: {
    // 当前联系人的消息列表
    messages () {
      const contact = this.$store.state.chatInformation.chatInformation.filter(
        item => item.id === this.current_contact.id && item.id_type === this.current_contact.id_type
      )[0]
      if (contact) {
        return contact.messages
      } else {
        return []
      }
    },
    // 当前联系人的id和类型
    current_contact () {
      return this.$store.state.chatInformation.current_contact
    },
    // 当前被删除消息ID
    deleteMsgID () {
      return this.$store.state.chatInformation.deleteMsgID
    }
  },
  watch: {
    messages: {
      immediate: true,
      deep: true,
      handler (val, oldVal) {
        if (val.length) {
          // this.$refs.messageContent
          const contact = this.$store.state.chatInformation.chatInformation.filter(
            item => item.id === this.current_contact.id && item.id_type === this.current_contact.id_type
          )[0]
          if (val && oldVal && val[0] && oldVal[0] && contact.ifBottom) {
            this.toBottom()
          }
        }
      }
    }
  },
  methods: {
    toBottom () {
      if (this.$refs.messageContent) {
        // this.$refs.messageContent
        this.$nextTick(() => {
          if (this.$refs && this.$refs.messageContent) {
            const currentHeight = this.$refs.messageContent.clientHeight
            const currentScrollHeight = this.$refs.messageContent.scrollHeight
            this.$refs.messageContent.scrollTo(
              0,
              currentScrollHeight - currentHeight + 0.48 * this.$_currentRem
            )
          }
        })
      }
    },
    // 查看历史消息
    showHistory (e) {
      const scrollTop = this.$refs.messageContent.scrollTop
      const wheelDelta = e.wheelDelta || e.detail
      if (wheelDelta > 0) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        if (!scrollTop) {
          this.timer = setTimeout(() => {
            if (this.messages.length) {
              sendSock({
                type: '5.2.5',
                body: {
                  id_type: this.current_contact.id_type,
                  id: this.current_contact.id,
                  page_size: 10,
                  msg_id: this.messages.filter(item => !item.special)[0].msg_id
                }
              })
              this.$store.commit('socket/set_operationReqId', 'pullHistoryRecordReqId')
            } else {
              sendSock({
                type: '5.2.4',
                body: {
                  id_type: this.current_contact.id_type,
                  id: this.current_contact.id,
                  page: 1,
                  page_size: 10
                }
              })
              this.$store.commit('socket/set_operationReqId', 'pullHistoryRecordReqId')
            }
            clearTimeout(this.timer)
          }, 100)
        }
      }
    },
    // 隐藏右键菜单
    hideRightList () {
      if (this.$store.state.message.ifShowMsgRightList) {
        this.$store.commit('message/set_ifShowMsgRightList', null)
      }
    },
    // 确认删除消息
    confirmDelete () {
      if (this.current_contact.id_type === 1) {
        this.$store.dispatch('chatInformation/deleteUserMessage', {
          targetID: this.current_contact.id,
          messageIDS: [this.deleteMsgID]
        })
      } else {
        this.$store.dispatch('chatInformation/deleteGroupMessage', {
          groupID: this.current_contact.id,
          groupMessages: [this.deleteMsgID]
        })
      }
      this.$store.commit('chatInformation/set_deleteMsgID', null)
    },
    // 取消删除消息
    cancelDelete () {
      console.log('cancel')
      this.$store.commit('chatInformation/set_deleteMsgID', null)
    }
  },
  mounted () {
    this.toBottom()
    this.$refs.messageContent.addEventListener('scroll', this.hideRightList)
  },
  beforeDestroy () {
    this.$refs.messageContent.removeEventListener('scroll', this.hideRightList)
  }
}
</script>

<style scoped lang="scss">
.chatContent {
  position: absolute;
  top: 72px;
  bottom: 200px;

  .content {
    height: 100%;
    padding: 24px 24px 0;
    //background-color: plum;

    .userMessageBox {
      position: relative;
    }
  }
}
</style>
